package com.changgou.oauth.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author tang.qingbo
 * @Date 2020/9/5 17:38
 * @Version 1.0
 */
public class FeignInterceptor implements RequestInterceptor {

    /**
     * feign底层就是restTemplate,在调用其他微服务前,组装之前请求过来的参数信息
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                //获取request
                HttpServletRequest request = attributes.getRequest();
                //获取所有头文件
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        //获取当前请求头中的key
                        String name = headerNames.nextElement();
                        //根据key获取对应的value
                        String values = request.getHeader("name");
                        //添加到头文件中
                        requestTemplate.header(name, values);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
